//
//  FirstPageViewController.m
//  Consume100
//
//  Created by eliot on 16/3/22.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "FirstPageViewController.h"
#import "FirstPageTableViewCell.h"
#import "RecommendTableViewCell.h"
#import "ImageTableViewCell.h"
#import "ButtonTableViewCell.h"
#import "CrowdfundingTableViewCell.h"
#import "ShoppingCenterTableViewController.h"
#import "StoreViewController.h"
#import "MyParnerViewController.h"
#import "PopularStoreViewController.h"
#import "CrowdFundingTableViewController.h"
#import "ProductViewController.h"
#import "MerchantsBrandViewController.h"
#import "UIImageView+WebCache.h"
#import "SZQRCodeViewController.h"
#import "AreaViewController.h"
#import "SearchFriendOrSessionViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface FirstPageViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, CLLocationManagerDelegate>

//顶部图片
@property (nonatomic, strong) UIScrollView *sc;
/** 滚动页点*/
@property (nonatomic ,strong) UIPageControl *page;
@property (weak, nonatomic) IBOutlet UITableView *bottomTableView;


@property (nonatomic ,strong) NSTimer *timer;

@property (nonatomic, strong) UISearchBar *searchBar;

@property (nonatomic, strong) UILabel *regionLb;

///**保存区域数组*/
//@property (nonatomic , strong) NSArray *cityArr;
/**城市视图*/
@property (nonatomic, strong) UIView *cityView;
/** 记录所在区域*/
@property (nonatomic, strong) UILabel *regionViewlabel;

/** 背景视图*/
@property (nonatomic, strong) UIView *blackView;
@property (nonatomic, strong) UIView *tabBarBlackView;

/** 右侧添加视图*/
@property (nonatomic, strong) UIView *addView;


@property (nonatomic, strong) UIView *titleView;

/** 滚动图片 数组*/
@property (nonatomic , strong) NSArray *imgArr;

/** 众筹图 数组*/
@property (nonatomic , strong) NSArray *croundArr;

/** 商家 数组*/
@property (nonatomic , strong) NSArray *storeArr;

/** 购物中心 数组*/
@property (nonatomic , strong) NSArray *shopCenterArr;



@property (nonatomic, strong) UIButton *topBtn;
@property (nonatomic, strong) UIButton *btn2;

@property (nonatomic) BOOL isSelected;

@property (nonatomic) BOOL rightIsSelected;

@property (nonatomic) int indexRegion ;


/** 位置*/
@property (nonatomic, strong) NSString *location;
@property (nonatomic, strong) CLLocationManager *locationManager;
/** 经度*/
@property (nonatomic, strong) NSString *longitude;
/** 纬度*/
@property (nonatomic, strong) NSString *latitude;


@end

@implementation FirstPageViewController


#pragma mark 定位
- (void)initializeLocationService {
    // 初始化定位管理器
    _locationManager = [[CLLocationManager alloc] init];
    // 设置代理
    _locationManager.delegate = self;
    // 设置定位精确度到米
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置每隔10米重新定位
    // _locationManager.distanceFilter = kCLDistanceFilterNone;
    _locationManager.distanceFilter = 10.0f;
    [_locationManager requestAlwaysAuthorization];//这句话ios8以上版本使用。
    
    // 开始定位
    [_locationManager startUpdatingLocation];
}



#pragma mark - 定位代理

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    
    CLLocation * currLocation = [locations lastObject];
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            //将获得的所有信息显示到label上
            self.location = placemark.name;
            //获取城市
            NSString *city = placemark.locality;
            if (!city) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                city = placemark.administrativeArea;
            }
            self.regionLb.text = city;
            
            NSLog(@"*****%@, %@, %@", placemark.name, city, placemark.subLocality);
            self.location = city;
        }
        else if (error == nil && [array count] == 0)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"定位失败，请移驾网络好的地方"];
            });
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
    
    [manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    //将经度显示到label上
    self.longitude = [NSString stringWithFormat:@"%lf", newLocation.coordinate.longitude];
    //将纬度现实到label上
    self.latitude = [NSString stringWithFormat:@"%lf", newLocation.coordinate.latitude];
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            //将获得的所有信息显示到label上
            self.location = placemark.name;
            //获取城市
            NSString *city = placemark.locality;
            if (!city) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                city = placemark.administrativeArea;
            }
            self.regionLb.text = city;
            self.regionViewlabel.text = [NSString stringWithFormat:@"  所在城市:%@", city];
            self.location = city;
        }
        else if (error == nil && [array count] == 0)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"定位失败，请移驾网络好的地方"];
            });
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    
    
    [manager stopUpdatingLocation];

    
}



#pragma mark - 懒加载

//-(NSArray *)cityArr {
//    if (!_cityArr) {
//        _cityArr = @[@"天河区",
//                     @"番禺区",
//                     @"越秀区",
//                     @"白云区"];
//    }
//    return _cityArr;
//}
- (UIScrollView *)sc {
    if (!_sc) {
        _sc = [[UIScrollView alloc] init];
    }
    return _sc;
}


-(UIPageControl *)page {
    if (!_page) {
        _page = [[UIPageControl alloc] init];
        [self.bottomTableView addSubview:_page];
        _page.frame = CGRectMake(0, Width / 2.0 - 20, Width, 20);
        [_page setAlpha:1];
    }
    return _page;
}


/** 设置滚动视图*/
- (void)setMyScrollView {
    self.sc.showsHorizontalScrollIndicator = NO;
    self.sc.frame = CGRectMake(0, 0, Width, Width / 2.0);
    //创建页点
    [self createsCrollView:nil];
}


#pragma ------创建视图区域----------
//创建滚动视图区域
- (void)createsCrollView:(id)sender {
    //设置委托
    self.sc.delegate = self;
    //将是否取消对内容视图触摸的反应设为NO
    self.sc.canCancelContentTouches = NO;
    //设置滚动条类型
    // self.scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    //是否可以缩放
    self.sc.scrollEnabled = YES;
    //是否可以进行页面切换
    self.sc.pagingEnabled = YES;
    NSUInteger page = 0;//为了记录页数
    int originX = 0;
    //填充滑动视图内容
    for (NSDictionary *imageDic in self.imgArr) {
        //首先创建一个视图
        UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectZero];
        imageview.contentMode = UIViewContentModeScaleToFill;
        //为这个图片设置适当位置
        CGRect rect ;
        rect.origin.x = originX;
        rect.origin.y = 0;
        rect.size.width = Width;
        rect.size.height = Width / 2.0;
        imageview.frame = rect;
        //设置图片为背景
        [imageview sd_setImageWithURL:[NSURL URLWithString:imageDic[@"img"]]];
        //添加到视图中
        [self.sc addSubview:imageview];
        //确定下张图片开始的x坐标
        originX += Width;
        //记录页数
        page++;
    }
    //设置总页数
    self.page.numberOfPages = page;
    //设置默认页为首页
    self.page.currentPage = 0;
    self.page.tag = 100;
    //为页数控制关联方法
    [self.page addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
    //显示适当区域
    [self.sc setContentSize:CGSizeMake(originX, Width / 2.0)];
}
- (void)repartScroll {
    if (self.page.currentPage == self.imgArr.count - 1) {
        self.page.currentPage = 0;
        [self.sc setContentOffset:CGPointMake(0, 0) animated:NO];
        
    }else{
        self.page.currentPage = self.page.currentPage + 1;
    }
    CGRect rect;
    rect.origin.x = self.page.currentPage * self.sc.frame.size.width;
    rect.origin.y = 0;
    rect.size.width = Width;
    rect.size.height = Width / 2.0;
    //设置滚动视图的可视区域
    [self.sc scrollRectToVisible:rect animated:YES];
    
}

//点击小点切换页面
- (void)changePage:(id)sender {
    //创建一个区域
    CGRect rect;
    rect.origin.x = self.page.currentPage * self.sc.frame.size.width;
    rect.origin.y = 0;
    rect.size.width = self.sc.frame.size.width;
    rect.size.height = self.sc.frame.size.height;
    //设置滚动视图的可视区域
    [self.sc scrollRectToVisible:rect animated:YES];
    
}

//重写滑动结束后的反应，就是把pageConteol的当前页跟随滑动而动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //取滚动视图区域的宽
    float orginX = self.sc.frame.size.width;
    //利用当前视图显示区域到view.frame的偏移量，来换算获取当前处在第几页
    int page = ((self.sc.contentOffset.x - orginX))/orginX +1;
    //当前页改为这一页。
    self.page.currentPage = page;
}


#pragma mark - 系统方法

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.timer invalidate];
}

//页面将要进入前台，开启定时器
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.rightIsSelected = NO;
    self.isSelected = NO;
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    //开启定时器
    [self.timer setFireDate:[NSDate distantPast]];
}

//页面消失，进入后台不显示该页面，关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
    //关闭定时器
    [self.timer setFireDate:[NSDate distantFuture]];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    self.addView.frame = CGRectMake(Width - 115, 0, 100, 0);
    self.cityView.frame = CGRectMake(2, 0, Width - 4, 0);
    self.blackView.hidden = YES;
    self.tabBarBlackView.hidden = YES;
    self.isSelected = NO;
    [self.titleView endEditing:YES];
   
}


-(UIView *)tabBarBlackView {
    if (!_tabBarBlackView) {
        //灰色背景
        _tabBarBlackView = [[UIView alloc] initWithFrame:self.tabBarController.tabBar.bounds];
        [self.tabBarController.tabBar addSubview:_tabBarBlackView];
        _tabBarBlackView.backgroundColor = [UIColor colorWithRed:205/255.0 green:205/255.0 blue:205/255.0 alpha:0.35];
    }
    return _tabBarBlackView;
}

-(UIView *)blackView {
    if (!_blackView) {
        //灰色背景
        _blackView = [[UIView alloc] initWithFrame:self.view.bounds];
        [self.view addSubview:_blackView];
        _blackView.backgroundColor = [UIColor colorWithRed:205/255.0 green:205/255.0 blue:205/255.0 alpha:0.60];
    }
    return _blackView;
}



-(UIView *)addView {
    if (!_addView) {
        _addView = [[UIView alloc] init];
        _addView.layer.cornerRadius = 10;
        _addView.layer.masksToBounds = YES;
        _addView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_addView];
        self.addView.frame = CGRectMake(Width - 115, 0, 100, 115);
        UIImageView *shareIV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_Share"]];
        [_addView addSubview:shareIV];
        shareIV.contentMode =  UIViewContentModeScaleAspectFit;
        [shareIV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(15);
            make.left.mas_equalTo(10);
            make.height.mas_equalTo(20);
            make.width.mas_equalTo(20);
        }];
        UILabel *lb = [[UILabel alloc] init];
        [_addView addSubview:lb];
        lb.backgroundColor = [UIColor colorWithRed:205/255.0 green:205/255.0 blue:205/255.0 alpha:1];
        [lb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.top.mas_equalTo(55);
            make.height.mas_equalTo(1);
        }];
        
        UILabel *lb1 = [[UILabel alloc] init];
        lb1.text = @"分享";
        [_addView addSubview:lb1];
        lb1.textColor = [UIColor colorWithRed:86/255.0 green:86/255.0 blue:86/255.0 alpha:1];
        [lb1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(shareIV.mas_right).mas_equalTo(4);
            make.top.right.mas_equalTo(0);
            make.height.mas_equalTo(55);
        }];
        UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addView addSubview:btn1];
        btn1.backgroundColor = [UIColor clearColor];
        [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.mas_equalTo(0);
            make.height.mas_equalTo(55);
        }];
        
        
        UIImageView *scanIV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_scan"]];
        [_addView addSubview:scanIV];
        [scanIV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(-15);
            make.height.mas_equalTo(20);
            make.width.mas_equalTo(20);
            make.left.mas_equalTo(10);
        }];
        scanIV.contentMode =  UIViewContentModeScaleAspectFit;
        
        
        UILabel *lb2 = [[UILabel alloc] init];
        lb2.text = @"扫一扫";
        [_addView addSubview:lb2];
        lb2.textColor = [UIColor colorWithRed:86/255.0 green:86/255.0 blue:86/255.0 alpha:1];
        [lb2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(scanIV.mas_right).mas_equalTo(4);
            make.right.bottom.mas_equalTo(0);
            make.height.mas_equalTo(55);
        }];
        UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addView addSubview:btn2];
        btn2.backgroundColor = [UIColor clearColor];
        [btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.mas_equalTo(0);
            make.height.mas_equalTo(79.5);
        }];
        [btn1 addTarget:self action:@selector(shareBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [btn2 addTarget:self action:@selector(scanBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addView;
}


-(UIView *)cityView {
    if (!_cityView) {
//        int count ;
//        if (self.cityArr.count % 3 == 0) {
//            count = (int)self.cityArr.count / 3;
//        }else {
//            count = (int)self.cityArr.count / 3 + 1;
//        }
        _cityView = [[UIView alloc] init];
        [self.blackView addSubview:_cityView];
        _cityView.frame = CGRectMake(2, 0, Width - 4, 40);

//        for (int j = 0; j < self.cityArr.count; j ++) {
//            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//            btn.layer.cornerRadius = 8;
//            btn.layer.masksToBounds = YES;
//            btn.backgroundColor = [UIColor whiteColor];
//            [btn setTitle:self.cityArr[j] forState:UIControlStateNormal];
//            [btn setTitleColor:[UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1] forState:UIControlStateNormal];
//            btn.tag = j;
//            [btn addTarget:self action:@selector(clickRegion:) forControlEvents:UIControlEventTouchUpInside];
//            [_cityView addSubview:btn];
//            if (j % 3 == 0) {
//                [btn mas_makeConstraints:^(MASConstraintMaker *make) {
//                    make.left.mas_equalTo(10);
//                    make.top.mas_equalTo(j/3*40 +(j/3 +1)*15);
//                    make.size.mas_equalTo(CGSizeMake((Width - 44)/3, 40));
//                }];
//            }
//            if (j % 3 == 1) {
//                [btn mas_makeConstraints:^(MASConstraintMaker *make) {
//                    make.left.mas_equalTo((Width - 44)/3 + 20);
//                    make.top.mas_equalTo(j/3*40 +(j/3 +1)*15);
//                    make.size.mas_equalTo(CGSizeMake((Width - 44)/3, 40));
//                }];
//            }
//            if (j % 3 == 2) {
//                [btn mas_makeConstraints:^(MASConstraintMaker *make) {
//                    make.right.mas_equalTo(-10);
//                    make.top.mas_equalTo(j/3*40 +(j/3 +1)*15);
//                    make.size.mas_equalTo(CGSizeMake((Width - 44)/3, 40));
//                }];
//            }
//        }
//        UILabel *label = [[UILabel alloc] init];
//        [_cityView addSubview:label];
//        label.backgroundColor = [UIColor colorWithRed:205/255.0 green:205/255.0 blue:205/255.0 alpha:1];
//        [label mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.right.mas_equalTo(0);
//            make.bottom.mas_equalTo(- 40);
//            make.height.mas_equalTo(1);
//        }];
        
        self.regionViewlabel = [[UILabel alloc] init];
        [_cityView addSubview:self.regionViewlabel];
        self.regionViewlabel.font = [UIFont systemFontOfSize:20];
        self.regionViewlabel.textColor = [UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1];
        self.regionViewlabel.text = @"所在城市：";
        [self.regionViewlabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.mas_equalTo(0);
            make.size.mas_equalTo(CGSizeMake(200, 40));
        }];
        
        UIButton *selectRegion = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cityView addSubview:selectRegion];
        [selectRegion setTitle:@"切换" forState:UIControlStateNormal];
        [selectRegion setTitleColor:[UIColor colorWithRed:46/255.0 green:110/255.0 blue:255/255.0 alpha:1] forState:UIControlStateNormal];
        [selectRegion addTarget:self action:@selector(changeCity) forControlEvents:UIControlEventTouchUpInside];
        [selectRegion mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.bottom.mas_equalTo(0);
            make.size.mas_equalTo(CGSizeMake(100, 40));
        }];
        
    }
//    _cityView.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
    _cityView.backgroundColor = [UIColor whiteColor];
    return _cityView;
}

/**点击区域*/
//- (void)clickRegion:(UIButton *)btn {
//    self.isSelected = !self.isSelected;
//    NSLog(@"选择的区域是：%@", btn.titleLabel.text);
////    int count ;
////    if (self.cityArr.count % 3 == 0) {
////        count = (int)self.cityArr.count / 3;
////    }else {
////        count = (int)self.cityArr.count / 3 + 1;
////    }
//    [UIView animateWithDuration:0.25 animations:^{
//
//        self.cityView.frame = CGRectMake(0, 0, Width - 4, 0);
//        
//        self.blackView.hidden = YES;
//    }];
//}

/**切换城市*/
- (void)changeCity {
    
    
    AreaViewController *vc = [[AreaViewController alloc] init];
    vc.isFromFirs = 100;
    [self creatNav:vc];

    vc.hadChoseArea = ^(NSString *area) {
        
        self.isSelected = NO;
        self.cityView.frame = CGRectMake(2, 0, Width - 4, 0);
        self.blackView.hidden = YES;
        self.regionLb.text =  area;
        
        self.regionViewlabel.text = [NSString stringWithFormat:@"  所在城市:%@", area];
 
    
    };
}


+(FirstPageViewController*)creatFirstPageViewController{
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    FirstPageViewController *first=[story instantiateViewControllerWithIdentifier:@"FirstPageViewController"];
    return first;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.cityView.hidden = NO;
    self.blackView.hidden = YES;
    self.rightIsSelected = NO;
    self.indexRegion = 0;
    self.isSelected = NO;
    
    [self initializeLocationService];
    
    /** 设置导航栏颜色*/
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    /** 注册*/
    [self.bottomTableView registerNib:[UINib nibWithNibName:@"FirstPageTableViewCell" bundle:nil] forCellReuseIdentifier:@"FirstPageTableViewCell"];
    [self.bottomTableView registerNib:[UINib nibWithNibName:@"RecommendTableViewCell" bundle:nil] forCellReuseIdentifier:@"RecommendTableViewCell"];
    [self.bottomTableView registerNib:[UINib nibWithNibName:@"ImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"ImageTableViewCell"];
    [self.bottomTableView registerNib:[UINib nibWithNibName:@"ButtonTableViewCell" bundle:nil] forCellReuseIdentifier:@"ButtonTableViewCell"];
    [self.bottomTableView registerNib:[UINib nibWithNibName:@"CrowdfundingTableViewCell" bundle:nil] forCellReuseIdentifier:@"CrowdfundingTableViewCell"];
    /** 设置搜索框*/
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
         [self setSearchBarOnNavigationItem];
    });
   
    /** 设置背景色*/
    self.view.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
    self.bottomTableView.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
    
    /** 设置右侧添加按钮*/
//    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_w_add"] style:UIBarButtonItemStylePlain target:self action:@selector(clickRightItem)];
//    self.navigationItem.rightBarButtonItem = rightBtn;
    
    /** 设置导航啦样式*/
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.navigationController.navigationBar.translucent = NO;
    
    /** 定时器*/
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.75 target:self selector:@selector(repartScroll) userInfo:nil  repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    /** 获取首页数据*/
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSString *baseUrl = [NSString stringWithFormat:@"%@getBanners.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dddic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.croundArr = [NSMutableArray arrayWithArray:dddic[@"crowdfundingList"]];
            
            self.imgArr = dddic[@"bannerList"];
            
            self.shopCenterArr = dddic[@"shopping"];
            
            self.storeArr = dddic[@"businessList"];
            [self.bottomTableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
}


/**点击左上角区域选择*/
- (void)choseRegionAtLeft:(UIButton *)btn {
    self.isSelected = !self.isSelected;
    self.rightIsSelected = NO;
//    int count ;
//    if (self.cityArr.count % 3 == 0) {
//        count = (int)self.cityArr.count / 3;
//    }else {
//        count = (int)self.cityArr.count / 3 + 1;
//    }
    
    if (self.isSelected) {
        [UIView animateWithDuration:0.25 animations:^{
            self.cityView.hidden = NO;
            self.blackView.hidden = NO;
            self.tabBarBlackView.hidden = NO;
            self.cityView.frame = CGRectMake(2, 0, Width - 4, 40);
            self.addView.frame = CGRectMake(Width - 115, 0, 100, 0);
        }];
    }else {
        [UIView animateWithDuration:0.25 animations:^{
            self.cityView.frame = CGRectMake(2, 0, Width - 4, 0);
            self.blackView.hidden = YES;
            self.tabBarBlackView.hidden = YES;
        }];
    }
}

//点击右侧添加按钮
- (void)clickRightItem {
    self.rightIsSelected = !self.rightIsSelected;
    self.isSelected = NO;
    self.addView.hidden = NO;
    if (self.rightIsSelected) {
        [UIView animateWithDuration:0.25 animations:^{
            self.addView.frame = CGRectMake(Width - 115, 0, 100, 115);
            self.cityView.frame = CGRectMake(2, 0, Width - 4, 0);
            self.cityView.hidden = YES;
            self.blackView.hidden = NO;
            self.tabBarBlackView.hidden = NO;
        }];
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            self.addView.frame = CGRectMake(Width - 115, 0, 100, 0);
            self.blackView.hidden = YES;
            self.tabBarBlackView.hidden = YES;
        }];
    }
}

/** 分享*/
- (void) shareBtnClick {
    
    self.blackView.hidden = YES;
    self.addView.hidden = YES;
    MyParnerViewController *vc = [MyParnerViewController CreatMyParnerViewController];
    [self creatNav:vc];
    

}

/** 扫一扫*/
- (void) scanBtnClick {
     NSLog(@"扫一扫");
    self.blackView.hidden = YES;
    self.addView.hidden = YES;
   
    self.tabBarController.tabBar.hidden = YES;
    SZQRCodeViewController *vc = [[SZQRCodeViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
}


#pragma mark - searchBar
- (void)setSearchBarOnNavigationItem {
    self.titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - self.navigationItem.rightBarButtonItem.width - 10, 35)];
    UIColor *color =  self.navigationController.navigationBar.barTintColor;
    [self.titleView setBackgroundColor:[UIColor clearColor]];
    self.searchBar = [[UISearchBar alloc] init];
    self.searchBar.delegate = self;
    self.searchBar.showsCancelButton = NO;
    self.searchBar.frame = CGRectMake(84, 0, self.view.frame.size.width - 50 - 10 - 84, 35);
    UIButton *bbbb = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.titleView addSubview:self.searchBar];
    [self.titleView addSubview:bbbb];
    bbbb.frame = CGRectMake(84, 0, self.view.frame.size.width - 50 - 10 - 84, 35);
    [bbbb addTarget:self action:@selector(aaa) forControlEvents:UIControlEventTouchUpInside];
    
    self.searchBar.backgroundColor = color;
    self.searchBar.layer.cornerRadius = 8;
    self.searchBar.layer.masksToBounds = YES;
    [self.searchBar.layer setBorderWidth:8];
    self.searchBar.tintColor=[UIColor blueColor];
    [self.searchBar.layer setBorderColor:[UIColor whiteColor].CGColor];  //设置边框为白色
    self.searchBar.placeholder = @"|搜索店铺";
    
    self.regionLb= [[UILabel alloc] init];
    self.regionLb.text = @"天河区";
    self.regionLb.frame = CGRectMake(0, 0, 60, 35);
    self.regionLb.textColor = [UIColor whiteColor];
    self.regionLb.font = [UIFont systemFontOfSize:20];
    [self.titleView addSubview:self.regionLb];
    
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(62, 12, 12, 12);
    [btn setBackgroundImage:[UIImage imageNamed:@"icon_D_arrow"] forState:UIControlStateNormal];
    [self.titleView addSubview:btn];
    self.topBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 74, 35)];
    [self.topBtn addTarget:self action:@selector(choseRegionAtLeft:) forControlEvents:UIControlEventTouchUpInside];
    self.topBtn.backgroundColor = [UIColor clearColor];
    [self.titleView addSubview:self.topBtn];
    
    
    self.btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
//    btn2.frame = CGRectMake(62, 12, 12, 12);
    [self.btn2 setBackgroundImage:[UIImage imageNamed:@"icon_w_add"] forState:UIControlStateNormal];
    [self.titleView addSubview:self.btn2];
    [self.btn2 addTarget:self action:@selector(clickRightItem) forControlEvents:UIControlEventTouchUpInside];
    [self.btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.top.mas_equalTo(7.5);
        make.bottom.mas_equalTo(-7.5);
        make.width.mas_equalTo(20);
    }];

    [self.titleView addSubview:self.btn2];

    //Set to titleView
    [self.navigationItem.titleView sizeToFit];
    self.navigationItem.titleView = self.titleView;
}



- (void)aaa {
    SearchFriendOrSessionViewController *view = [self.storyboard instantiateViewControllerWithIdentifier:@"SearchFriendOrSessionViewController"];
    //    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:view];
    //    nav.navigationBar.barTintColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    view.navigationItem.hidesBackButton = YES;
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:view animated:YES];

}

//- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
//    [self.searchBar resignFirstResponder];
//    
//    return NO;
//}
//点击搜索框
//- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
//    
//    
//    [searchBar resignFirstResponder];
//    SearchFriendOrSessionViewController *view = [self.storyboard instantiateViewControllerWithIdentifier:@"SearchFriendOrSessionViewController"];
////    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:view];
////    nav.navigationBar.barTintColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
//    view.navigationItem.hidesBackButton = YES;
//    self.tabBarController.tabBar.hidden = YES;
//    [self.navigationController pushViewController:view animated:YES];
//    //[self.navigationController pushViewController:view animated:YES];
//    
//    
// 
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


//点击美食城
- (void)clickFoodBtn:(id)sender {
    StoreViewController *vc = [StoreViewController CreatStoreViewController];
    vc.storetypeLb = @"美食城";
    vc.district = 1;
    
    vc.cityName = self.regionLb.text;
    [self creatNav:vc];
    
}

//点击商场商圈
- (void)clickShoppingBtn:(id)sender {
    StoreViewController *vc = [StoreViewController CreatStoreViewController];
    vc.storetypeLb = @"商场商圈";
    vc.district = 2;
    vc.cityName = self.regionLb.text;
    [self creatNav:vc];
}

//点击休闲娱乐
- (void)clickRecreationBtn:(id)sender {
    StoreViewController *vc = [StoreViewController CreatStoreViewController];
    vc.storetypeLb = @"休闲娱乐";
    vc.district = 3;
    vc.cityName = self.regionLb.text;
    [self creatNav:vc];
}

//点击KTV
- (void)clickKTVBtn:(id)sender {
    StoreViewController *vc = [StoreViewController CreatStoreViewController];
    vc.storetypeLb = @"KTV";
    vc.district = 4;
    vc.cityName = self.regionLb.text;
    [self creatNav:vc];
}

//点击时尚丽人
- (void)clickFashionBtn:(id)sender {
    StoreViewController *vc = [StoreViewController CreatStoreViewController];
    vc.storetypeLb = @"时尚丽人";
    vc.district = 5;
    vc.cityName = self.regionLb.text;
    [self creatNav:vc];
}

//点击超市
- (void)clickSupermarketBtn:(id)sender {
    StoreViewController *vc = [StoreViewController CreatStoreViewController];
    vc.storetypeLb = @"超市";
    vc.district = 6;
    vc.cityName = self.regionLb.text;
    [self creatNav:vc];
}
//点击美生活服务
- (void)clickLifeBtn:(id)sender {
    StoreViewController *vc = [StoreViewController CreatStoreViewController];
    vc.storetypeLb = @"生活服务";
    vc.district = 7;
    vc.cityName = self.regionLb.text;
    [self creatNav:vc];
}

#pragma mark - tableView (tableViewDelegate/tableViewDataSource)

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 5) {
        return 2;
    }else if (section == 0) {
        return 0;
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    tableView.showsVerticalScrollIndicator = NO;
    switch (indexPath.section) {
        case 0:
        {
          
            return nil;
        
        }
            break;
        case 1:
        {
            ButtonTableViewCell *btnCell = [tableView dequeueReusableCellWithIdentifier:@"ButtonTableViewCell" forIndexPath:indexPath];
            btnCell.selectionStyle = UITableViewCellSelectionStyleNone;
            [btnCell.foodBtn addTarget:self action:@selector(clickFoodBtn:) forControlEvents:UIControlEventTouchUpInside];
            [btnCell.tradBtn addTarget:self action:@selector(clickShoppingBtn:) forControlEvents:UIControlEventTouchUpInside];
            [btnCell.amusementBtn addTarget:self action:@selector(clickRecreationBtn:) forControlEvents:UIControlEventTouchUpInside];
            [btnCell.KTVBtn addTarget:self action:@selector(clickKTVBtn:) forControlEvents:UIControlEventTouchUpInside];
            [btnCell.fashionBtn addTarget:self action:@selector(clickFashionBtn:) forControlEvents:UIControlEventTouchUpInside];
            [btnCell.supermarketBtn addTarget:self action:@selector(clickSupermarketBtn:) forControlEvents:UIControlEventTouchUpInside];
            [btnCell.lifeBtn addTarget:self action:@selector(clickLifeBtn:) forControlEvents:UIControlEventTouchUpInside];
            return btnCell;
            
        }
            break;
        case 2:
        {
            FirstPageTableViewCell *firstCell = [tableView dequeueReusableCellWithIdentifier:@"FirstPageTableViewCell" forIndexPath:indexPath];
            [firstCell setUpCellWithArr:self.storeArr];
            firstCell.selectionStyle = UITableViewCellSelectionStyleNone;
            [firstCell.allBtn addTarget:self action:@selector(clickHotStoreBtn) forControlEvents:UIControlEventTouchUpInside];
            [firstCell.btn1  addTarget:self action:@selector(clickHotStoreBtn:) forControlEvents:UIControlEventTouchUpInside];
            [firstCell.btn2  addTarget:self action:@selector(clickHotStoreBtn:) forControlEvents:UIControlEventTouchUpInside];
            [firstCell.btn3  addTarget:self action:@selector(clickHotStoreBtn:) forControlEvents:UIControlEventTouchUpInside];
            return firstCell;
            
        }
            break;
        case 3:
        {
            CrowdfundingTableViewCell *crowdCell = [tableView dequeueReusableCellWithIdentifier:@"CrowdfundingTableViewCell" forIndexPath:indexPath];
            crowdCell.selectionStyle = UITableViewCellSelectionStyleNone;
            [crowdCell.allCrowdFundingBtn addTarget:self action:@selector(clickallCrowdFundingBtn) forControlEvents:UIControlEventTouchUpInside];
            [crowdCell setUpCellWithArr:self.croundArr];
            crowdCell.selectionStyle = UITableViewCellSelectionStyleNone;
            [crowdCell.btn1  addTarget:self action:@selector(clickHotPurchasesBtn:) forControlEvents:UIControlEventTouchUpInside];
            [crowdCell.btn2  addTarget:self action:@selector(clickHotPurchasesBtn:) forControlEvents:UIControlEventTouchUpInside];
            [crowdCell.btn3  addTarget:self action:@selector(clickHotPurchasesBtn:) forControlEvents:UIControlEventTouchUpInside];
           
            
            return crowdCell;
            
        }
            break;
        case 4:
        {
            FirstPageTableViewCell *firstCell = [tableView dequeueReusableCellWithIdentifier:@"FirstPageTableViewCell" forIndexPath:indexPath];
            firstCell.iconIV.image = [UIImage imageNamed:@"icon_shoppingC"];
            firstCell.selectionStyle = UITableViewCellSelectionStyleNone;
            firstCell.titleLb.text = @"购物中心";
            firstCell.firstIV.layer.cornerRadius = 8;
            firstCell.firstIV.layer.masksToBounds = YES;
            firstCell.secondIV.layer.cornerRadius = 8;
            firstCell.secondIV.layer.masksToBounds = YES;
            firstCell.thridIV.layer.cornerRadius = 8;
            firstCell.thridIV.layer.masksToBounds = YES;
            [firstCell.allBtn addTarget:self action:@selector(clickShoppingCenterAllBtn) forControlEvents:UIControlEventTouchUpInside];
            
            
            firstCell.btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
            firstCell.btn1.frame = CGRectMake(firstCell.firstIV.frame.origin.x
                                         , firstCell.firstIV.frame.origin.y, firstCell.firstIV.frame.size.width, firstCell.firstIV.frame.size.height + 30);
            
            firstCell.btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
            firstCell.btn2.frame = CGRectMake(firstCell.secondIV.frame.origin.x
                                         , firstCell.secondIV.frame.origin.y, firstCell.secondIV.frame.size.width, firstCell.secondIV.frame.size.height + 30);
            
            firstCell.btn3 = [UIButton buttonWithType:UIButtonTypeCustom];
            firstCell.btn3.frame = CGRectMake(firstCell.thridIV.frame.origin.x
                                         , firstCell.thridIV.frame.origin.y, firstCell.thridIV.frame.size.width, firstCell.thridIV.frame.size.height + 30);
            
            firstCell.btn1.tag = 1;
            firstCell.btn2.tag = 2;
            firstCell.btn3.tag = 3;
            
            [firstCell addSubview:firstCell.btn1];
            [firstCell addSubview:firstCell.btn2];
            [firstCell addSubview:firstCell.btn3];
            
            firstCell.btn1.userInteractionEnabled = NO;
            firstCell.btn2.userInteractionEnabled = NO;
            firstCell.btn3.userInteractionEnabled = NO;
            
            firstCell.selectionStyle = UITableViewCellSelectionStyleNone;
            [firstCell.btn1  addTarget:self action:@selector(clickShoppingCenterBtn:) forControlEvents:UIControlEventTouchUpInside];
            [firstCell.btn2  addTarget:self action:@selector(clickShoppingCenterBtn:) forControlEvents:UIControlEventTouchUpInside];
            [firstCell.btn3  addTarget:self action:@selector(clickShoppingCenterBtn:) forControlEvents:UIControlEventTouchUpInside];
            
            
            
            
            
            [firstCell.secondIV sd_setImageWithURL:[NSURL URLWithString:@""]];
            firstCell.secondLb.text = @"";
            
            [firstCell.thridIV sd_setImageWithURL:[NSURL URLWithString:@""]];
            firstCell.thridLb.text = @"";
            
            
            
            for (int i = 0; i < self.shopCenterArr.count; i++) {
                NSDictionary *tepDic = self.shopCenterArr[i];
                if (i == 0) {
                    [firstCell.firstIV sd_setImageWithURL:[NSURL URLWithString:tepDic[@"img"]]];
                    firstCell.firstLb.text = tepDic[@"name"];
                    firstCell.btn1.userInteractionEnabled = YES;
                }
                if (i == 1) {
                    [firstCell.secondIV sd_setImageWithURL:[NSURL URLWithString:tepDic[@"img"]]];
                    firstCell.secondLb.text = tepDic[@"name"];
                    firstCell.btn2.userInteractionEnabled = YES;
                }
                if (i == 2) {
                    [firstCell.thridIV sd_setImageWithURL:[NSURL URLWithString:tepDic[@"img"]]];
                    firstCell.thridLb.text = tepDic[@"name"];
                    firstCell.btn3.userInteractionEnabled = YES;
                }
                
            }
            
            
            
            return firstCell;
            
        }
            break;
        default:
        {
            RecommendTableViewCell *recommendCell = [tableView dequeueReusableCellWithIdentifier:@"RecommendTableViewCell" forIndexPath:indexPath];
            recommendCell.selectionStyle = UITableViewCellSelectionStyleNone;
            return recommendCell;
            
            
        }
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return Width / 2.0;
    }else if (section == 5){
        return 36;
    }else {
        return 15;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
            return  0;
            break;
        case 1:
            return 210;
            break;
        case 2:
            return 200;
            break;
        case 3:
            return 230;
            break;
        case 4:
            return 200;
            break;
            
        default:
            return 99;
            break;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewAutomaticDimension;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        
        [self setMyScrollView];
        return self.sc;
    }else if (section == 5) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 36)];
        UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_-Recommend"]];
        iv.contentMode =  UIViewContentModeScaleAspectFit;
        [view addSubview:iv];
        [iv mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.mas_equalTo(4);
            make.size.mas_equalTo(CGSizeMake(29, 26));
        }];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(37, 10, 83, 21)];
        label.text = @"推荐";
        label.font = [UIFont systemFontOfSize:17];
        [view addSubview:label];
        view.backgroundColor = [UIColor whiteColor];
        UILabel *backgroundLb = [[UILabel alloc] init];
        [view addSubview:backgroundLb];
        [backgroundLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(0);
            make.height.mas_equalTo(2);
        }];
        backgroundLb.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
        return view;
    }else {
        return nil;
    }
   
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 4) {
       
    }

    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [self.titleView endEditing:YES];
}

//创建模态导航控制器
-(void)creatNav:(UIViewController *)view{
    
    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:view];
    nav.navigationBar.barTintColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    view.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_back"] style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    [self.navigationController pushViewController:view animated:YES];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)dismiss {
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}


/** 点击热门  商家  下面的图片  根据tag判断点的第几张*/
- (void)clickHotStoreBtn:(UIButton *)sender {
    
    ProductViewController *vc = [ProductViewController CreatProductViewController];
    [self creatNav:vc];

}


/** 点击热门  众筹  下面的图片  根据tag判断点的第几张*/
- (void)clickHotPurchasesBtn:(UIButton *)sender {
    
   
    
}

/** 点击  购物中心  下面的图片  根据tag判断点的第几张*/
- (void)clickShoppingCenterBtn:(UIButton *)sender {
    MerchantsBrandViewController *vc = [MerchantsBrandViewController CreatMerchantsBrandViewController];
    [self creatNav:vc];
    
}

/** 点击  购物中心 全部*/
- (void)clickShoppingCenterAllBtn {
    ShoppingCenterTableViewController *vc = [ShoppingCenterTableViewController CreatShoppingCenterTableViewController];
    [self creatNav:vc];
}




/** 点击  热门商家  全部*/
- (void)clickHotStoreBtn {
    PopularStoreViewController *vc = [PopularStoreViewController CreatPopularStoreViewController];
    [self creatNav:vc];
}

/** 点击  热门众筹  全部*/
- (void)clickallCrowdFundingBtn {
    CrowdFundingTableViewController *vc = [CrowdFundingTableViewController CreatCrowdFundingTableViewController];
    [self creatNav:vc];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
